package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.C2DMPushInfo;
import net.ib.mntalk.protocol.Common.PushInfo;
import net.ib.mntalk.protocol.Session.SetUserDeviceInfoReq;
import net.ib.mntalk.protocol.Session.SetUserDeviceInfoRes;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.google.protobuf.micro.ByteStringMicro;

public class SetUserDeviceInfoTask extends AsyncNetTask {

	public SetUserDeviceInfoTask(Context _context) {
		super(_context);
	}

	@Override
	protected TcpEnvelope onPreExecute() {
		C2DMPushInfo c2dmPushInfo = new C2DMPushInfo();
		c2dmPushInfo.setRegistrationId(GlobalPreferences.getRegistrationId());
		
		PushInfo pushInfo = new PushInfo();
		pushInfo.setC2DmPush(c2dmPushInfo);
		pushInfo.setType(Common.C2DMPush);

		//String deviceId = ((TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
		String deviceId = Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
		SetUserDeviceInfoReq req = new SetUserDeviceInfoReq();
		req.setDeviceId(ByteStringMicro.copyFromUtf8(deviceId));
		req.setAppUuid(GlobalPreferences.getAppUUID());
		req.setPushInfo(pushInfo);
		
		TcpEnvelope revelop = new TcpEnvelope.Builder()
		.setType(TcpEnvelope.REQUEST)
		.setMessage(req)
		.setMethodId(Session.User.SetUserDeviceInfo)
		.build();

		MTalkLogWriter.i("SetUserDeviceInfoTask.onPostExecute(): Try to deliver C2DM Registration ID lately.");
		return revelop;
	}

	@Override
	protected void onPostExecute(int resultCode, Object sentObject, Object receivedObject) {
		if (receivedObject == null) {
			MTalkLogWriter.i("SetUserDeviceInfoTask.onPostExecute(): Fail to deliver C2DM Registration ID lately.");
			return;
		}

		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		SetUserDeviceInfoRes setUserDeviceInfoRes = (SetUserDeviceInfoRes) resultEnvelope.getMessage();
		
		if (setUserDeviceInfoRes.getResponseCode() == Common.SUCCESS) {
			GlobalPreferences.setRegistrationIdLocated(true);
			MTalkLogWriter.i("SetUserDeviceInfoTask.onPostExecute(): Succeed to deliver C2DM Registration ID lately.");
		} else {
			GlobalPreferences.setRegistrationIdLocated(false);
			MTalkLogWriter.i("SetUserDeviceInfoTask.onPostExecute(): Fail to deliver C2DM Registration ID lately.");
		}
	}

}
